package com.hinner.config.security;

import cn.hutool.core.util.StrUtil;
import com.hinner.common.CheckResult;
import com.hinner.common.JwtConstant;
import com.hinner.entity.SysUser;
import com.hinner.service.SysUserService;
import com.hinner.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;


public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private MyUserDetailsServiceImpl myUserDetailsService;

    private static final String[] URL_WHITELIST = {
            "/login",
            "/logout",
            "/captcha",
            "/password",
            "/image/**"
    } ;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    /**
     * 主要验证token
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("token");
        System.out.println("token = " + token);
        System.out.println("请求url = " + request.getRequestURI());
        // 当前系统如果登录成功后肯定是有token的
        // 如果token为空【请求登录接口时token为空，肯定也要放行】，或者在白名单中，直接放行
        if (StrUtil.isBlank(token) || Arrays.asList(URL_WHITELIST).contains(request.getRequestURI())){
            chain.doFilter(request,response);
            return;
        }
        // token不空，就要验证token
        CheckResult checkResult = JwtUtils.validateJWT(token);
        if (!checkResult.isSuccess()) {
            switch (checkResult.getErrCode()){
                case JwtConstant.JWT_ERRCODE_FAIL: throw new JwtException("token验证不通过");
                case JwtConstant.JWT_ERRCODE_EXPIRE: throw new JwtException("token已过期");
                case JwtConstant.JWT_ERRCODE_NULL: throw new JwtException("token不存在");
            }
        }
        // 成功，获取主体信息Claims
        Claims claims = JwtUtils.parseJWT(token);
        String username = claims.getSubject();
        SysUser sysUser = sysUserService.getUserByUserName(username);
        // 放到上下文中
        /*
            void setAuthentication(Authentication var1);
            实现类用：UsernamePasswordAuthenticationToken
         */
        UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(sysUser, null, myUserDetailsService.getAuthorities(sysUser.getId()));
        SecurityContextHolder.getContext().setAuthentication(upat);
        //放行
        chain.doFilter(request,response);
    }
}
